<?php

namespace SunAdmin\Service;

use SunAdmin\Common\Utils;
use SunAdmin\Model\DataDictionaryModel;
use think\Exception;
use think\facade\Cache;

class DataDictionaryService
{
    public static $cacheTag = "sun_admin_data_dictionary_";

    public static function edit($data)
    {
        if (empty($data['name']) || empty($data['key'])) {
            throw new Exception("名称/key不能为空");
        }
        if (!$data['is_cate']) {
            if (empty($data['value'])) {
                throw new Exception('参数值不能为空');
            }
        }else{
            if(empty($data['cate_id_path'])){
                $data['cate_id'] = 0;
            }else{
                $data['cate_id'] = $data['cate_id_path'] ? $data['cate_id_path'][count($data['cate_id_path']) - 1] : 0;
            }
        }
        if (empty($data['id'])) {
            //判断key是否存在于数据库,不能重复
            $keyIsIn = DatadictionaryModel::where("key", $data['key'])->find();
            if (!empty($keyIsIn)) {
                throw new Exception("存在重复的key值,重复项名称[{$keyIsIn['name']}]");
            }
            DataDictionaryModel::create($data);
        } else {
            $oldInfo = DataDictionaryModel::where("id", $data['id'])->find();
            if (empty($oldInfo)) {
                throw new Exception('该配置项不存在');
            }
            if ($oldInfo->is_cate != $data['is_cate']){
                throw new Exception('参数[是否类目分组]不可更改');
            }
            DataDictionaryModel::update($data, ['id' => $data['id']]);
        }
        if (!$data['is_cate']) {
            Cache::tag(self::$cacheTag)->set(self::$cacheTag . $data['key'], $data['value']);
        }
        return true;
    }

    public static function del($id)
    {
        if (empty($id)){
            throw new Exception("id不能为空");
        }
        $data = DataDictionaryModel::find($id);
        if (empty($data)) {
            throw new Exception("数据不存在或已删除");
        }
        if($data['is_cate']){
            $cateInnerDataCount = DataDictionaryModel::where(['cate_id'=>$id])->count();
            if($cateInnerDataCount>0){
                throw new Exception("类目下存在配置数据项目,不可以删除");
            }
        }
        $data->delete();
        if (!$data['is_cate']) {
            Cache::delete(self::$cacheTag . $data['key']);
        }
        return true;
    }

    /**
     * 获取类目下的配置项
     */
    public static function getCateInnerDataList($cateId){
        if (empty($cateId)) {
            throw new Exception("类目id不能为空");
        }
        $list = DataDictionaryModel::where(['is_cate'=>0,'cate_id'=>$cateId])->select()->toArray();
        return $list;
    }


    /**
     * 获取配置值,优先从缓存获取
     * 如果是单个配置,返回值. 如果是多个配置,返回数组
     */
    public static function getValue(array|string $keys, $fromDb = false)
    {
        if (empty($keys)) {
            return [];
        }
        if (!is_array($keys)) {
            $keys = [$keys];
        }
        if ($fromDb) {
            $res = DataDictionaryModel::whereIn("key", $keys)->column('value', 'key');
        } else {
            $res = [];
            foreach ($keys as $key) {
                $res[$key] = Cache::get(self::$cacheTag . $key);
            }
        }
        if (count($res) == 1) {
            return $res[$keys[0]];
        }
        return $res;
    }

    /**
     * 强制更新所有缓存
     * 1删除标签下所有缓存
     * 2从数据库读取数据循环写入标签
     */
    public static function updateCacheData()
    {
        Cache::tag(self::$cacheTag)->clear();
        $dbData = DataDictionaryModel::where('is_cate', 0)->column('value', 'key');
        foreach ($dbData as $k => $v) {
            Cache::tag(self::$cacheTag)->set(self::$cacheTag . $k, $v);
        }
        return true;
    }

    /**
     * 获取类目分组
     */
    public static function getCateTreeList()
    {
        $list = DataDictionaryModel::where('is_cate', 1)->select()->toArray();
        $tree = Utils::buildTree($list, 0, 'cate_id');
        return $tree;
    }
}